<template>
  <div>
    <a-card class="card" :bordered="false" :style="`min-height: ${cardMinHeight}px;`">

      <!--弹窗0 新增按钮-->
      <a-modal
          destroyOnClose
          class="addModal"
          v-model='addModal'
          width='1200px'
          :title="isAdd?'新增':title"
          @ok="submit"
          @cancel="handleCancel0"
          :bodyStyle="bodyStyle"
      >
        <a-spin :spinning="spinning">
                  <div style="width: 100%;margin: 10px auto">
                    <div style="display: flex;justify-content: space-between;margin-bottom: 10px;">
                      <a-input style='width: 150px;height: 32px;margin-right: 10px'
                               placeholder="申请编码" v-model.trim="addForm.requestCode" :disabled="!canBeEdited || !isAdd"></a-input>
                      <a-input style='width: 150px;height: 32px;
                          margin-right: 10px' placeholder="备件序号" v-model.trim="addForm.id" disabled></a-input>
                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '160px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in partSearchList" :key="index"  @click="changePart(item)" >{{'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                        <a-input style='width: 150px;height: 32px;
                          margin-right: 10px' placeholder="*备件编码"
                                 v-model.trim="addForm.code"
                                 @keydown.enter="getPartIdByCodeLimit(addForm.code)"
                                 @change="getPartIdByCodeLimit(addForm.code)"
                                 @click="getPartIdByCodeLimit(addForm.code)"
                                 allowClear
                                 :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-popover trigger="click" placement="bottom" :overlayStyle="{ width: '160px' }">
                        <template slot="content">
                          <p class="aPopover" v-for="(item,index) in partSearchList" :key="index"  @click="changePart(item)" >{{'code:'+item.code+',name:'+item.name}}</p>
                        </template>
                        <a-input style='width: 150px;height: 32px;margin-right: 10px'
                                 placeholder="*名称"
                                 v-model.trim="addForm.name"
                                 @keydown.enter="getPartIdByNameLimit(addForm.name)"
                                 @change="getPartIdByNameLimit(addForm.name)"
                                 allowClear
                                 :disabled="!canBeEdited || !isAdd"></a-input>
                      </a-popover>

                      <a-date-picker
                          show-time
                          allow-clear
                          format="YYYY-MM-DD"
                          placeholder="日期"
                          v-model.trim="addForm.date"
                          @change="onChangeDate"
                          style='width: 120px;height: 32px;margin-right: 10px'
                          :disabled="!canBeEdited || !isAdd"
                      />
                      <a-input style='width: 120px;height: 32px;' placeholder="数量" v-model.trim="addForm.number" :disabled="!canBeEdited || !isAdd"></a-input>
                      <div style="width: 247px;display: flex;  justify-content:right">
                        <a-button type="primary" style="margin-right: 15px" @click="clearAddMessage" :disabled="!canBeEdited || !isAdd">重置</a-button>
                        <a-button type="primary" @click="addPart" :disabled="!canBeEdited || !isAdd|| !this.addForm.code || !this.addForm.number || !this.addForm.date || !this.addForm.requestCode">添加</a-button>
                      </div>

                    </div>

                    <a-table
                        :columns="key1Columns"
                        :data-source="key1Data"
                        :pagination="key1Pagination"
                        @change="onChangeKey1"
                        :showPagination="true"
                        :loading="tableLoading01"
                        :scroll="{x:true,y: 165 }"
                    >
                      <template slot="action" slot-scope="record1">
                        <a-popconfirm title="确定删除?" @confirm="() => delExtend(record1)">
                          <a>删除</a>
                        </a-popconfirm>
                      </template>
                    </a-table>
                  </div>

        </a-spin>

      </a-modal>
      <page-head-area>
        <div class="extra" style="width: 200px;display: flex;justify-content: space-around">
          <a-button icon="plus-circle" v-auth="`insert`" @click="add" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">新增</a-button>
          <a-popconfirm title="批量删除?" @confirm="deleteSelect">
            <a-button icon="delete" v-auth="`delete`" style="background-color: #fff;border: none;margin-left: 10px;width: 70px;height: 35px;">删除</a-button>
          </a-popconfirm>
<!--          <a-button icon="audit"  style="background-color: #eeeeee;border: none;margin-left: 10px;width: 70px;height: 35px;">审核</a-button>-->
        </div>
      </page-head-area>

      <div class="queryBox">
        <a-form-model layout="inline" :model='queryForm' ref="queryFormRef" class='query' style='display: flex;flex-wrap: wrap;'>
          <a-form-model-item
              label="编码"
          >
            <a-input style='width: 200px;height: 32px' v-model='queryForm.code' v-auth="`query`"></a-input>
          </a-form-model-item>

          <a-form-model-item
              label="日期范围"
              prop="date"
              ref="dateRef"
          >
            <a-range-picker
                :allow-clear="true"
                :valueFormat="'YYYY-MM-DD'"
                :format="'YYYY-MM-DD'"
                v-model.trim="queryForm.dateSelect"
                />
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="reset" v-auth="`query`">
              重置
            </a-button>
          </a-form-model-item>

          <a-form-model-item>
            <a-button type='primary' style='height: 32px;width: 70px;text-align: center' @click="filter" v-auth="`query`">
              搜索
            </a-button>
          </a-form-model-item>
        </a-form-model>
      </div>
      <div class="dataBox">
        <a-table
            :columns="columns"
            :data-source="data"
            :pagination="false"
            :loading="tableLoading"
            :rowKey="(recordMain) => {return recordMain.id}"
            :scroll="{ x: 1000, y: 500 }"
            :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        >
          <template slot="action" slot-scope="record">
            <a v-auth="`query`" >详情</a>
          </template>
        </a-table>

      </div>
      <a-pagination
          @change="onChangePage"
          @showSizeChange="showSizeChange"
          :total="pagination.total"
          :showSizeChanger="true"
          :showQuickJumper="true"
          :defaultPageSize="pagination.defaultPageSize"
          :pageSize="pagination.page_size"
          :pageSizeOptions="pagination.pageSizeOptions"
          :current="pagination.current"
          :showTotal="pagination.showTotal"
          style="width: 100%;display: flex;flex-direction: row;justify-content: flex-end;margin-top: 15px"
      ></a-pagination>
    </a-card>
  </div>
</template>

<script>

import {mapGetters} from "vuex";
import PageHeadArea from "../module/pageHeadArea.vue";
import storage from "store";
import {ORGANIZATION_ID} from "@/store/mutation-types";
import axios from "axios";
import {delete_asset} from "@/services/manage";
import {
  deleteDeviceInspection, deleteSparePartsRequest,
  getCurrentUserInfo,
  getDeviceList,
  getPartsById,
  getSparePartsRequestList,
  getUserNameById,
  saveSparePartsRequest, saveSparePartsRequestPartsRelation
} from "../../utils/interface";
import {message} from "ant-design-vue";
import {get_spare_parts_request_list} from "../../services/deviceManagement";

const data = []
const columns = [
  { title: '申请单号', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '申请人', width: 120, align:'center',dataIndex: 'requester_name', key: 'requester_name'},
  { title: '申请日期', width: 120, align:'center',dataIndex: 'create_time', key: 'create_time'},
  { title: '审核状态', width: 120, align:'center',dataIndex: 'audit_name', key: 'audit_name'},
  { title: '状态', width: 120, align:'center',dataIndex: 'status_name', key: 'status_name'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 180,
    scopedSlots: { customRender: 'action' }
  }
]

const key1Columns = [
  { title: '申请编码', width: 120, align:'center',dataIndex: 'requestCode', key: 'requestCode'},
  { title: '序号', width: 120, align:'center',dataIndex: 'id', key: 'id'},
  { title: '编码', width: 120, align:'center',dataIndex: 'code', key: 'code'},
  { title: '名称', width: 120, align:'center',dataIndex: 'name', key: 'name'},
  { title: '日期', width: 120, align:'center',dataIndex: 'date', key: 'date'},
  { title: '数量', width: 120, align:'center',dataIndex: 'number', key: 'number'},
  {
    title: '操作',
    align:'center',
    key: 'operation',
    fixed: 'right',
    width: 120,
    scopedSlots: { customRender: 'action' }
  }]



const key1Data =[];

export default {
  name: "userAuthority",
  components: {PageHeadArea},
  data() {
    return {
      statusNameList:[
        {code:0,description: '未入库'},
        {code:1,description: '已入库'},
      ],
      selectedRowKeys:[],
      partSearchList:[],
      addForm:{
        requestCode:undefined,
        id:undefined,
        code:undefined,
        name:undefined,
        date:'',
        number:undefined,
      },
      auditStatusList:[
        { code: 0, description: "未审核" },
        { code: 1, description: "已审核" },
      ],//状态列表
      key1Data,
      key1Columns,
      tableLoading01: false,

      axiosSource: null,
      tabKey: '1',
      title:'',
      tabBarGutter: 0,
      tabBarStyle: {
        color: 'rgba(0, 0, 0, 0.85)'
      },
      bodyStyle: {
        'padding': '0px 24px 0px 24px',
        'font-size': '14px',
        'line-height': '1.5',
        'word-wrap': 'break-word',
      },
      cardMinHeight: 0,
      queryForm: {
        code: undefined,
        name: undefined,
        dateSelect:[]

      },
      data,
      columns,
      pagination: {
        total: 0,
        page_size: 10,
        defaultPageSize: 10,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['10', '20', '50', '100', '500'],
      },
      tableLoading: false,
      addModal: false,
      canBeEdited: false, //是否可编辑
      isAdd: false, //是否为新增
      spinning: false,

      detailModal:false, //详情弹窗
      canBeQuery:false, //是否可查询

      key1Pagination: {
        total: 0,
        page_size: 4,
        defaultPageSize: 4,
        page: 1,
        current: 1,
        showSizeChanger: true,
        showQuickJumper: true,
        showTotal: total => `共 ${total} 条记录`,
        pageSizeOptions: ['4', '8', '10', '20', '50'],
      },
    }
  },
  watch: {},
  authorize: {
    add: 'insert',
    getAssetLedgerList: 'query',
    reset: 'query',
    query: 'query',
    detail: 'query',
    edit: 'update',
    del: 'delete',
    check: 'check',
  },
  computed: {
    ...mapGetters(['getCardMinHeight']),
  },
  created() {
    this.cardMinHeight = this.getCardMinHeight
  },
  async mounted() {
    // this.axiosSource = axios.CancelToken.source();

    await this.initialize()
  },
  methods: {
    onSelectChange(selectedRowKeys) {
      // console.log('selectedRowKeys changed: ', selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },
    async filter() {
      //筛选
      this.pagination.page = 1
      this.pagination.current = 1
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize({
        'code': this.queryForm.code
      })
      // this.dataFilter = this.data.filter(item => {
      //   // 检查每个条件是否满足
      //   return (
      //       (this.queryForm.code ?  item.code && item.code.includes(this.queryForm.code) : true) &&
      //       (startDate ? new Date(item.request_time) >= new Date(startDate) : true) &&
      //       (endDate ? new Date(item.request_time) <= new Date(endDate) : true)
      //   );
      // });
      this.tableLoading = false;
    },
    onChangeDate(value, dateString){
      this.addForm.date = dateString
    },
    async getPartIdByCodeLimit(code) {
      await getPartsById({'code': code}).then(res => {
        //添加res中值到supplierSearchList
        this.partSearchList = []
        res.slice(0, 10).forEach(item => {
          this.partSearchList.push({
            id: item.id,
            code: item.code,
            name: item.name,
          })
        })
      })
    },
    delExtend(record1){
      this.key1Data = this.key1Data.filter(item => item !== record1);
    },
    async getPartIdByNameLimit(name) {
      await getPartsById({'name': name}).then(res => {
        //添加res中值到supplierSearchList
        this.partSearchList = []
        res.slice(0, 10).forEach(item => {
          this.partSearchList.push({
            id: item.id,
            code: item.code,
            name: item.name,
          })
        })
      })
    },
    changePart(item) {
      this.addForm.id= item.id
      this.addForm.code= item.code
      this.addForm.name= item.name
      this.partSearchList=[]
    },
    onChangePage (page, pageSize) {
      this.pagination.current = page
      this.pagination.page_size = pageSize
      this.pagination.page = page
      this.initialize()
    },
    showSizeChange(current, size){
      this.pagination.page_size = size
      this.pagination.current = current
      this.pagination.page = current
      this.initialize()
    },
    clearAddMessage(){
      this.addForm={
        requestCode:undefined,
        id:undefined,
        code:undefined,
        name:undefined,
        date:'',
        number:undefined,
      }
      this.partSearchList=[]
    },
    async addPart() {
      //查重code
      const isDuplicate = this.key1Data.some(item => item.requestCode === this.addForm.requestCode);

      if (isDuplicate) {
        message.error('列表中存在重复的申请编码');
        return;
      }
      //查code
      let searchCodeList = await getSparePartsRequestList(
          {'code': this.addForm.requestCode})

      let flag = true
      if(searchCodeList.length>0){
        for(const item of searchCodeList){
          if(item.code===this.addForm.requestCode){
            flag = false
            break
          }
        }
      }
      if(flag===false){
        message.error('申请编码已存在');
        return;
      }

      this.key1Data.push({
        'requestCode': this.addForm.requestCode,
        'id': this.addForm.id,
        'code': this.addForm.code,
        'name': this.addForm.name,
        'date': this.addForm.date,
        'number': this.addForm.number,

      })
      console.log(this.key1Data)
      this.clearAddMessage()
      // console.log(this.addForm)
    },
    async initialize(params) {
      this.tableLoading = true
      this.data = []

      const paramsAll = Object.assign({}, params, {
        "page": this.pagination.page,
        "page_size": this.pagination.page_size
      });
      await get_spare_parts_request_list(paramsAll).then(async res => {
        if (res.data.code !== '1000') {
          this.tableLoading = false
          this.data = []
        } else {
          this.pagination.total = res.data.extension.total+(this.pagination.current-1)*this.pagination.page_size
          for (const item of res.data.data) {
            item['requester_name'] = await getUserNameById(item.requester_id)
            item['audit_name'] = this.auditStatusList.find(itemIn => itemIn.code === item.request_status)?.description || ''
            item['status_name'] = this.statusNameList.find(itemIn => itemIn.code === item.status)?.description || ''
          }
        }
        // 获取时间范围
        const [startDate, endDate] = this.queryForm.dateSelect;
        this.data = res.data.data.filter(itemRes => {
          return (
              (!startDate || new Date(itemRes.request_time) >= new Date(startDate)) &&
              (!endDate || new Date(itemRes.request_time) <= new Date(endDate))
          );
        });
      })
      this.tableLoading = false
    },
    callback (key) { // assetCode
      this.tabKey = key
    },
    // 分页切换
    onChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.page_size = pagination.pageSize
      this.pagination.page = pagination.current
      this.getAssetLedgerList()
    },
    // 分页切换
    onChangeKey1 (pagination) {
      this.key1Pagination.current = pagination.current
      this.key1Pagination.page_size = pagination.pageSize
      this.key1Pagination.page = pagination.current
    },
    async query() {
      this.pagination.page = 1
      this.pagination.current = 0
      this.pagination.page_size = 10
      this.tableLoading = true
      await this.initialize()
      this.tableLoading = false
    },
    reset() {
      this.queryForm = {
        code: undefined,
        name: undefined,
        dateSelect:[]
      }
      this.query()
    },
    add() {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = true
      this.spinning = false
      this.key1Data=[]
    },
    async deleteSelect() {
      for (const item of this.selectedRowKeys) {
        await deleteSparePartsRequest({'id': item})
      }
      this.selectedRowKeys = []
      message.success('删除成功')
      await this.initialize()
    },
    edit(record) {
      this.addModal = true
      this.canBeEdited = true
      this.isAdd = false
      this.echo(record)
    },
    detail(record) {
      this.detailModal = true
      this.canBeEdited = false
      this.canBeQuery =true
      this.isAdd = false
      this.echo(record)
    },
    clearParameter() {},
    handleCancel() {
      this.tabKey = '1'
    },
    handleCancel0() {
      this.addModal = false
      this.clearAddMessage()
      this.canBeEdited = false
      this.isAdd = false
    },
    handleCancel1(){
      this.detailModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    handleCancel2(){
      this.disposalModal = false
      this.canBeEdited = false
      this.canBeQuery =false
      this.isAdd = false
    },
    async submit() {
      // message.info("开始新增")
      let user = await getCurrentUserInfo()
      //user_id
      let user_id = user.user_id
      for (const it of this.key1Data) {
        await saveSparePartsRequest({
          'code':it.requestCode,
          'requester_id':user_id,
          'request_time':it.date,
        })
        let searchRequest = await getSparePartsRequestList({'code':it.requestCode})
        let id2
        for(const item of searchRequest){
          if(item.code===it.requestCode){
            id2=item.id
            break
          }
        }
        await saveSparePartsRequestPartsRelation({
          'request_id':id2,
          'parts_id':it.id,
          'quantity':it.number,

        })
        this.handleCancel0()
        message.success("新增成功")
        await this.initialize()
      }
    },
  },
  beforeDestroy() {
    if (this.axiosSource) {
      this.axiosSource.cancel('Request canceled due to page navigation.');
    }
  }
}
</script>

<style scoped lang="less">
.aPopover{
}
.aPopover:hover {
  background-color: #EA5413;
}
.dataBox{
  margin-top: 20px;
}

.hide-scrollbar::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}

::-webkit-scrollbar {
  display: none; /* 隐藏滚动条 */
}
.hide-scrollbar {
  -ms-overflow-style: none;  /* IE 和 Edge */
  scrollbar-width: none;  /* Firefox */
  overflow-y: scroll; /* 保持内容可滚动 */
}
.demo-infinite-container {
  margin-top: 0px;
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  overflow: auto;
  padding: 8px 24px;
  height: 300px;
}
/deep/ .ant-form-inline .ant-form-item-with-help{
  margin-bottom: 0px;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #f5f5f5;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .unit .ant-select-selection--single{
  margin-left: 0px;
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-left: 0;
}
/deep/ .ant-select-disabled .ant-select-selection {
  background-color: #fff;
}
/deep/ .ant-input[disabled]{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
/deep/ .ant-input-number-disabled{
  pointer-events: none;
  color: #000000d9;
  background-color: #fff;
  cursor: not-allowed;
  opacity: 1;
}
</style>